#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import pymysql
from config import Config, get_database
from models.sleep_monitoring import SleepMonitoringRecord

def test_direct_mysql_connection():
    """直接测试MySQL连接"""
    print("🔍 直接测试MySQL连接...")
    try:
        connection = pymysql.connect(
            host=Config.DB_HOST,
            port=Config.DB_PORT,
            user=Config.DB_USER,
            password=Config.DB_PASSWORD,
            database=Config.DB_NAME,
            charset='utf8mb4'
        )
        
        with connection.cursor() as cursor:
            # 检查数据库版本
            cursor.execute("SELECT VERSION()")
            version = cursor.fetchone()
            print(f"✅ MySQL版本: {version[0]}")
            
            # 检查当前数据库
            cursor.execute("SELECT DATABASE()")
            current_db = cursor.fetchone()
            print(f"✅ 当前数据库: {current_db[0]}")
            
            # 检查表是否存在
            cursor.execute("SHOW TABLES")
            tables = cursor.fetchall()
            print(f"✅ 数据库中的表: {[table[0] for table in tables]}")
            
            # 检查sleep_monitoring_records表的记录数
            if ('sleep_monitoring_records',) in tables:
                cursor.execute("SELECT COUNT(*) FROM sleep_monitoring_records")
                count = cursor.fetchone()
                print(f"✅ sleep_monitoring_records表记录数: {count[0]}")
                
                if count[0] > 0:
                    cursor.execute("SELECT session_id, room_id, start_time FROM sleep_monitoring_records ORDER BY created_at DESC LIMIT 1")
                    record = cursor.fetchone()
                    print(f"✅ 最新记录: 会话ID={record[0][:8]}..., 房间={record[1]}, 时间={record[2]}")
            else:
                print("⚠️  sleep_monitoring_records表不存在")
        
        connection.close()
        return True
        
    except Exception as e:
        print(f"❌ 直接MySQL连接失败: {e}")
        return False

def test_peewee_connection():
    """测试Peewee ORM连接"""
    print("\n🔍 测试Peewee ORM连接...")
    try:
        db = get_database()
        print(f"✅ 数据库对象类型: {type(db)}")
        print(f"✅ 数据库配置: {db.database}@{db.host}:{db.port}")
        
        db.connect()
        print("✅ Peewee连接成功")
        
        # 检查表是否存在
        table_exists = SleepMonitoringRecord.table_exists()
        print(f"✅ 表是否存在: {table_exists}")
        
        if table_exists:
            count = SleepMonitoringRecord.select().count()
            print(f"✅ 记录数: {count}")
        
        db.close()
        return True
        
    except Exception as e:
        print(f"❌ Peewee连接失败: {e}")
        return False

def check_sqlite_file():
    """检查SQLite文件是否仍在使用"""
    print("\n🔍 检查SQLite文件...")
    import os
    sqlite_file = 'eeg_signal_dispatcher.db'
    
    if os.path.exists(sqlite_file):
        size = os.path.getsize(sqlite_file)
        print(f"⚠️  SQLite文件仍存在: {sqlite_file} (大小: {size} bytes)")
        
        # 检查SQLite文件的最后修改时间
        import datetime
        mtime = os.path.getmtime(sqlite_file)
        mtime_str = datetime.datetime.fromtimestamp(mtime).strftime('%Y-%m-%d %H:%M:%S')
        print(f"⚠️  SQLite文件最后修改时间: {mtime_str}")
        
        return True
    else:
        print("✅ SQLite文件不存在")
        return False

def main():
    """主函数"""
    print("🚀 验证数据库连接类型...")
    print(f"📊 配置信息:")
    print(f"   DB_HOST: {Config.DB_HOST}")
    print(f"   DB_PORT: {Config.DB_PORT}")
    print(f"   DB_NAME: {Config.DB_NAME}")
    print(f"   DB_USER: {Config.DB_USER}")
    print()
    
    # 检查SQLite文件
    sqlite_exists = check_sqlite_file()
    
    # 测试直接MySQL连接
    mysql_direct = test_direct_mysql_connection()
    
    # 测试Peewee连接
    peewee_works = test_peewee_connection()
    
    print("\n📋 总结:")
    if mysql_direct and peewee_works:
        print("✅ 确认使用MySQL数据库")
        if sqlite_exists:
            print("⚠️  建议删除旧的SQLite文件")
    elif sqlite_exists and not mysql_direct:
        print("❌ 可能仍在使用SQLite数据库")
    else:
        print("❌ 数据库连接存在问题")

if __name__ == '__main__':
    main()